// 路由状态管理
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { persist } from 'zustand/middleware';
import { 
  ViewType, 
  NavigationItem, 
  BreadcrumbItem, 
  RouterState, 
  RouterActions,
  DEFAULT_NAVIGATION_ITEMS 
} from '../types/router';

interface RouterStore extends RouterState, RouterActions {}

const initialState: RouterState = {
  currentPath: '/editor',
  currentView: ViewType.EDITOR,
  navigationItems: DEFAULT_NAVIGATION_ITEMS,
  breadcrumbs: [{ label: '编辑器', path: '/editor', icon: 'file-text' }],
  isNavigating: false,
};

export const useRouterStore = create<RouterStore>()(
  subscribeWithSelector(
    persist(
      (set, get) => ({
        ...initialState,

        navigate: (path: string, viewType?: ViewType) => {
          const state = get();
          
          // 防止重复导航
          if (state.currentPath === path && !state.isNavigating) {
            return;
          }

          set({ isNavigating: true });

          // 确定视图类型
          let targetViewType = viewType;
          if (!targetViewType) {
            const navItem = state.navigationItems.find(item => item.path === path);
            targetViewType = navItem?.viewType || ViewType.EDITOR;
          }

          // 更新面包屑
          const navItem = state.navigationItems.find(item => item.path === path);
          const newBreadcrumbs: BreadcrumbItem[] = [];
          
          if (navItem) {
            newBreadcrumbs.push({
              label: navItem.label,
              path: navItem.path,
              icon: navItem.icon,
            });
          }

          // 模拟导航延迟
          setTimeout(() => {
            set({
              currentPath: path,
              currentView: targetViewType!,
              breadcrumbs: newBreadcrumbs,
              isNavigating: false,
            });
          }, 100);
        },

        goBack: () => {
          // 简单的后退实现
          window.history.back();
        },

        goForward: () => {
          // 简单的前进实现
          window.history.forward();
        },

        setNavigationItems: (items: NavigationItem[]) => {
          set({ navigationItems: items });
        },

        setBreadcrumbs: (breadcrumbs: BreadcrumbItem[]) => {
          set({ breadcrumbs });
        },

        updateNavigationBadge: (id: string, badge?: string | number) => {
          const state = get();
          const updatedItems = state.navigationItems.map(item =>
            item.id === id ? { ...item, badge } : item
          );
          set({ navigationItems: updatedItems });
        },
      }),
      {
        name: 'router-store',
        partialize: (state) => ({
          currentPath: state.currentPath,
          currentView: state.currentView,
          navigationItems: state.navigationItems,
        }),
      }
    )
  )
);

// 选择器
export const useCurrentView = () => useRouterStore(state => state.currentView);
export const useCurrentPath = () => useRouterStore(state => state.currentPath);
export const useNavigationItems = () => useRouterStore(state => state.navigationItems);
export const useBreadcrumbs = () => useRouterStore(state => state.breadcrumbs);
export const useIsNavigating = () => useRouterStore(state => state.isNavigating);

// 导航操作
export const useNavigation = () => {
  const navigate = useRouterStore(state => state.navigate);
  const goBack = useRouterStore(state => state.goBack);
  const goForward = useRouterStore(state => state.goForward);
  
  return { navigate, goBack, goForward };
};
